package org.chen.task;

import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.chen.common.utils.SnowflakeIdGenerator;
import org.chen.domain.entity.AvatarGroup;
import org.chen.client.HeyGenClient;
import org.chen.mapper.AvatarGroupMapper;
import org.chen.response.KeyAvatarGroupResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Component
@Slf4j
public class AvatarGroupSyncTask {
    @Autowired
    private HeyGenClient heyGenClient;

    @Autowired
    private AvatarGroupMapper avatarGroupMapper;

    private static final int BATCH_SIZE = 500; // 每批处理的数据量

    @Scheduled(cron = "0 0 2 * * *")
//    @Scheduled(fixedRateString = "60000")
    @Transactional
    public void syncAvatarGroup() {
        log.info("Start syncing AvatarGroup...");
        try {
            // 1. 获取API数据
            KeyAvatarGroupResponse response = heyGenClient.getKeyAvatarGroup();
            if (response == null || response.getData() == null ||
                    response.getData().getAvatar_group_list() == null) {
                log.error("Invalid AvatarGroup response");
                return;
            }

            // 2. 获取现有数据
            List<String> existingAvatarIds = avatarGroupMapper.selectAllAvatarIds();

            // 3. 分类处理
            List<AvatarGroup> toInsert = new ArrayList<>();
            List<AvatarGroup> toUpdate = new ArrayList<>();

            List<org.chen.response.AvatarGroup> avatarGroupList = response.getData().getAvatar_group_list();
            for (org.chen.response.AvatarGroup group : avatarGroupList) {
                AvatarGroup avatarGroup = convertToEntity(group);
                if (existingAvatarIds.contains(group.getId())) {
                    toUpdate.add(avatarGroup);
                } else {
                    toInsert.add(avatarGroup);
                }
            }

            // 4. 分批处理插入
            if (!toInsert.isEmpty()) {
                Lists.partition(toInsert, BATCH_SIZE).forEach(batch -> {
                    avatarGroupMapper.batchInsert(batch);
                    log.info("Inserted {} avatars", batch.size());
                });
            }

            // 5. 分批处理更新
            if (!toUpdate.isEmpty()) {
                Lists.partition(toUpdate, BATCH_SIZE).forEach(batch -> {
                    avatarGroupMapper.batchUpdate(batch);
                });
            }

            log.info("Avatar sync completed successfully");
        } catch (Exception e) {
            log.error("Avatar sync failed", e);
        }
    }

    private AvatarGroup convertToEntity(org.chen.response.AvatarGroup avatarGroup) {
        AvatarGroup entity = new AvatarGroup();
        // 使用雪花算法生成ID
        entity.setId(SnowflakeIdGenerator.nextId());
        entity.setAvatarId(avatarGroup.getId());
        entity.setAvatarName(avatarGroup.getName());
        entity.setPreviewImageUrl(avatarGroup.getPreview_image_url());
        entity.setGroupType(avatarGroup.getGroup_type());
        entity.setNumLooks(avatarGroup.getNum_looks());
        entity.setCreatedAtFromTimestamp(avatarGroup.getCreated_at());
        entity.setTrainStatus(avatarGroup.getTrain_status());
        return entity;
    }
}
